<script setup lang="ts">
import {message} from 'ant-design-vue';
import {useForm, useModal, z} from '#/ui-kit';
import {useDictStore} from '#/stores';

import {findUserList} from '#/api/system/user';
import {createDeptInfo, findDeptListTree, updateDeptInfo} from '#/api/system/dept';

const emits = defineEmits(['close']);

const {getDictData} = useDictStore();

const [Modal, modalApi] = useModal({
  draggable: true,
  closeOnClickModal: false,
  destroyOnClose: true,
  onConfirm: function () {
    formApi.validateAndSubmitForm();
  },
  onBeforeClose: function () {
    modalApi.setState({confirmLoading: false})
    modalApi.setData({});
    formApi.resetForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      formApi.setValues(modalApi.getData(), false, false);
    }
  }
});

const [Form, formApi] = useForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
      allowClear: true,
    },
  },
  layout: 'horizontal',
  showDefaultActions: false,
  schema: [
    {
      label: '部门名称',
      fieldName: 'name',
      component: 'Input',
      componentProps: {placeholder: '请输入部门名称'},
      rules: 'required',
    },
    {
      label: '所属上级',
      fieldName: 'parentId',
      component: 'ApiTreeSelect',
      componentProps: {
        api: findDeptListTree,
        showSearch: true,
        treeNodeFilterProp: 'name',
        fieldNames: {
          value: 'id',
          label: 'name',
          children: 'children',
        },
        treeDefaultExpandedKeys: [1],
        placeholder: '请选择所属上级',
      },
      dependencies: {
        show: ({parentId}) => {
          return parentId !== 0;
        },
        triggerFields: ['parentId'],
      },
      rules: z.number({required_error: '请选择所属上级'})
          .refine((value) => value != modalApi?.getData()?.id,
              {message: '当前选择项无法为所属上级'}),
    },
    {
      label: '负责人',
      fieldName: 'leaderId',
      component: 'ApiSelect',
      componentProps: {
        api: findUserList,
        placeholder: '请选择部门负责人',
        fieldNames: {
          value: 'id',
          label: 'nickname',
        }
      },
      rules: 'selectRequired',
    },
    {
      label: '排序',
      fieldName: 'sort',
      component: 'InputNumber',
      componentProps: {placeholder: '请输入排序'},
      defaultValue: 0,
      rules: 'required',
    },
    {
      label: '备注',
      fieldName: 'remark',
      component: 'Textarea',
      componentProps: {placeholder: '请输入备注'},
    },
    {
      label: '启用状态',
      fieldName: 'enableStatus',
      component: 'RadioGroup',
      componentProps: {
        options: getDictData('enable_status', true),
      },
      defaultValue: 0,
    },
  ],
  handleSubmit: function (values) {
    modalApi.setState({confirmLoading: true});
    if (values?.id) {
      updateDeptInfo(values).then(() => {
        message.success('部门信息更新成功');
        modalApi.close();
        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false});
      });
    } else {
      createDeptInfo(values).then(() => {
        message.success('部门信息新增成功');
        modalApi.close();
        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false});
      });
    }
  },
});
</script>

<template>
  <Modal>
    <Form/>
  </Modal>
</template>